<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getGoodsApi,
  getDepartmentTableApi,
  saveApi,
  deleteDepartmentApi,
  auditApi
} from '@/api/goods'
import type { DepartmentItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import Audit from './components/Audit.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { number } from 'vue-types'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getDepartmentTableApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.result,
      total: res.data.totalCount
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDepartmentApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'title',
    label: t('商品名称'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'description',
    label: t('描述'),
    search: {
      hidden: true
    }
  },
  {
    field: 'rawMaterial',
    label: t('原材料'),
    search: {
      hidden: true
    }
  },
  {
    field: 'price',
    label: t('单价'),
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 0
    }
  },
  {
    field: 'auditState',
    label: t('上架状态'),
    search: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: [
          {
            label: '已下架',
            value: 'Offline'
          },
          {
            label: '已上架',
            value: 'Online'
          }
        ]
        // options: [
        //   {
        //     label: '审批中',
        //     value: 'Approval'
        //   },
        //   {
        //     label: '已通过',
        //     value: 'Pass'
        //   },
        //   {
        //     label: '已拒绝',
        //     value: 'Reject'
        //   }
        // ]
      }
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime'),
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: '330px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              {/* <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton> */}
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="primary" onClick={() => action(data.row, 'audit')}>
                {t('审批')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any | null>(null)
const actionType = ref('')

const BatchAuditAction = () => {
  dialogTitle.value = t('批量审批')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'audit'
}

const delLoading = ref(false)

const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: any, type: string) => {
  if (type === 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
  } else if (type === 'detail') {
    dialogTitle.value = t('exampleDemo.detail')
  } else if (type === 'audit') {
    dialogTitle.value = '审批'
  }
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const auditRef = ref<ComponentRef<typeof Audit>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveApi(formData)
      .catch(() => { })
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const audit = async () => {
  const audit = unref(auditRef)
  const formData = await audit?.formAudit()
  if (formData) {
    const elTableExpose = await getElTableExpose()
    const gIds = currentRow.value
      ? [currentRow.value?.id]
      : elTableExpose?.getSelectionRows().map((v) => v.id) || []
    saveLoading.value = true
    const res = await auditApi({
      goodsIds: gIds,
      auditResult: formData.auditState,
      auditRemark: formData.auditRemark
    })
      .catch(() => { })
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="BatchAuditAction">{{ t('批量审批') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('批量删除') }}
      </BaseButton>
    </div>

    <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
      :data="dataList" :loading="loading" :pagination="{
        total: total
      }" @register="tableRegister" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail' && actionType !== 'audit'" ref="writeRef" :form-schema="allSchemas.formSchema"
      :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :detail-schema="allSchemas.detailSchema" :current-row="currentRow" />

    <Audit v-if="actionType === 'audit'" ref="auditRef" :form-schema="allSchemas.formSchema"
      :current-row="currentRow" />

    <template #footer>
      <BaseButton v-if="actionType === 'audit'" @click="audit">
        {{ '审批' }}
      </BaseButton>
      <BaseButton v-if="actionType !== 'detail' && actionType !== 'audit'" type="primary" :loading="saveLoading"
        @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
